package com.ngm.tea.t.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ngm.tea.BaseController;
import com.ngm.tea.t.entity.Account;
import com.ngm.tea.t.entity.Module;
import com.ngm.tea.t.service.AccountService;
import com.ngm.tea.t.service.ModuleService;

/**
 * 控制器
 * 
 * @author zjw
 * @version 1.0
 * @date 2016-09-01 21:07:07
 *
 */
@Controller
@RequestMapping(value = "/t/login")
public class LoginController extends BaseController {

	@Resource
	private ModuleService moduleService;
	@Resource
	private AccountService accountService;
	private String viewPath = "App/login/";

	@RequestMapping("/index")
	public String index(HttpServletRequest request) {
		return viewPath + "index";
	}

	@RequestMapping("/login")
	public String login(Account account, HttpServletRequest request) {
		Account _account = accountService.selectByNamePassword(account);
		if (_account == null) {
			request.setAttribute("msg", "用户名密码错误!");
			return viewPath + "index";
		} else {
			try {
				request.setAttribute("_account", _account);
				request.getSession().setAttribute("account", _account);
				Map<String, ArrayList<String>> roles = new HashMap<String, ArrayList<String>>();
				List<Map<String, String>> maps = accountService.roleList(_account);
				for (int s = 0; s < maps.size(); s++) {
					ArrayList<String> _list = null;
					Map<String, String> map = maps.get(s);
					if (roles.get(map.get("mod_code")) == null) {
						roles.put(map.get("mod_code"), new ArrayList<String>());
						_list = roles.get(map.get("mod_code"));
						_list.add(map.get("pri_code"));
					} else {
						_list = roles.get(map.get("mod_code"));
						_list.add(map.get("pri_code"));
					}
				}
				request.getSession().setAttribute("roles", roles);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "index";
		}
	}

	@RequestMapping("/selectMenu")
	public Object selectMenu(String code, HttpServletRequest request) {
		try {
			List<Module> list = moduleService.selectMenu(code);
			request.setAttribute("list", list);
			return "App/common/leftMenu";
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("InfoMessage", "信息载入失败！具体异常信息：" + e.getMessage());
			return viewPath + "result";
		}
	}

	@RequestMapping("/loginout")
	public String loginOut(HttpServletRequest request) {
		request.getSession().removeAttribute("account");
		return viewPath + "index";
	}

}